#include <stdlib.h>
#include <stdio.h>
#include <time.h>

/*	multi_informations.cpp
*	This program is part of the °Simple-Benchs° Benchmark
*	The complexity of this program is O(n) where n is the array's size
*
*	
*	To run the program:	./program array_size max_element
*/

/*	Display the generated data in the standart output. Complexity O(n) where n is the array's size*/
void display(int max, int min, long sum, float average,int size, int *array){
	int count;
	printf("Generated array:\n");
	for (count=0; count<size;count++){
		printf("%d ",array[count]);
	}
	printf("\nMaximun value of array = %d\n",max);
	printf("Minimum value of array = %d\n",min);
	printf("Sum of all elements    = %ld\n",sum);
	printf("Average = %.3f\n",average);
}

/* Performing some operations to generate useful data. Complexity O(n) where n is the array's size.
In this funcion we have an intereting behavior defined in the lines 36 and 38. The branches within the loop
demands a big amount of pairs to help in the complexity inference*/
void getInfo(int *array, int size){
	int count;
	int max = array[0];
	int min = array[0];
	long sum = array[0];
	float average;
	for (count = 1; count < size; count++){
		sum += array[count];
		if (array[count] > max)
			max = array[count];
		if (array[count] < min)
			min = array[count];
	}
	average = (float)sum/size;
	display(max,min,sum,average,size, array);
}


/* Array initialization. Complexity O(n) where n is the array's size*/
void initArray(int *vet, int size, int max) {
  int count;
  for (count = 0; count < size; count++)
    vet[count] = rand() % max;
}

/*	Auxiliar function that perform a simple linear search in the array. Complecity O(n) in the worst case, where the element is not
present in the array*/
void findNum(int *array, int size, int max_gen){
	int num = rand() % max_gen;
	int count;
	int flag = 0;
	for (count = 0; count < size; count++)
    if(num ==  array[count]){
    	flag = 1;
      	break;
    }
  if (flag == 1)
   	printf("The random number %d is present in the array\n", num);
  else
   	printf("The random number %d is not present in the array\n", num);
}

/*	Initial check to verify whether the amount of arguments is correct or not.  Complexity O(1)	*/
short Initial_check(int inputs){
  if (inputs != 3) {
  	fprintf(stderr, "Syntax: ./program array_size max_num\n");
    return 1;
  }
  return 0;
}


int main(int argc, char **argv){

	/* Checking arguments */
  if (Initial_check(argc)) return 1;

	/* Retrieve problem size. */
	int size = atoi(argv[1]);
	int max_gen = atoi(argv[2]);

	/* Seed initialization. */
  srand((unsigned)time(NULL));

	/* Variable declaration/allocation/initialization. */
	int *array = (int*)malloc(size*sizeof(int*));
	initArray(array,size,max_gen);

	/*	Performing the computation */
	getInfo(array, size);
	findNum(array, size, max_gen);

	/* Be clean. */
	free(array);
	return 0;
}